package shuzi.util;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import shuzi.data.Database;
import shuzi.model.Brand;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;

public class IconMap {
	
	private Bitmap bitmap = null;
	private MyThread thread = null;
	private static IconMap instance = null;

	public static IconMap getInstance(){
		if(instance==null){
			instance = new IconMap();
		}
		return instance;
	}

	/**
	 * 设置图片的背景
	 * 
	 * @param url
	 */
	public void setImageViewBg(Brand brand,String url, String keyName ,Handler handler,int what) {
		
		if(thread!=null){
			Log.v(Database.TAG, "keyName = "+keyName+"");
			thread.interrupt();
		}
		
		// 如果内存缓存为空
		if (Database.mLinkedHashMap == null) {
			Database.mLinkedHashMap = new HashMap<String, SoftReference<Bitmap>>();
		}

		// 如果包含了key
		if (Database.mLinkedHashMap.containsKey(keyName)) {
			SoftReference<Bitmap> softReference = Database.mLinkedHashMap
					.get(keyName);
			bitmap = softReference.get();
			// 如果不为空的话，直接使用
			if (bitmap != null) {
				// Log.v(Database.TAG, "keyName "+keyName+" 不为空");
				brand.setIcon(bitmap);
				handler.sendEmptyMessage(what);
			} else {
				Database.mLinkedHashMap.remove(keyName);
				//getBitmap(url, keyName);
				thread = new MyThread(brand,url, keyName,handler,what);
				thread.start();
			}
		} else { // 如果没有包含key
		//	getBitmap(url, keyName);
			thread = new MyThread(brand,url, keyName,handler,what);
			thread.start();
		}
	}

	class MyThread extends Thread {
		String url;
		String keyName;
		int what;
		Handler handler;
		Brand brand;

		public MyThread(Brand brand,String url, String keyName ,Handler handler,int what) {
			this.keyName =keyName;
			this.url = url;
			this.handler = handler;
			this.what = what;
			this.brand = brand;
		}

		@Override
		public void run() {
			super.run();
			try {
				//nowKeyName = keyName;
				byte[] data = Download.getImage(url);
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inPurgeable = true;
				options.inInputShareable = true;
				bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
						options);
				Database.mLinkedHashMap.put(keyName, new SoftReference<Bitmap>(
						bitmap));
				Log.v(Database.TAG, "keyName " + keyName + " 下载");
				brand.setIcon(bitmap);
				handler.sendEmptyMessage(what);
			} catch (Exception e) {
				//handler.sendEmptyMessage(0);
				e.printStackTrace();
			}
		}
	}

	
}
